import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate,useSearchParams } from 'react-router-dom'
import './index.scss'
import Editor from "@/components/Editor"
import { useState,useEffect} from 'react'
import {creatArticleAPI,updateArticle} from '@/apis/article'
import { useChannel } from '@/hooks/useChannel'
import {getArticleById} from '@/apis/article'      
const { Option } = Select
const Publish = () => { 
  const {channelList} = useChannel()// 获取频道列表       
  const navigate = useNavigate()
 const [imageList, setImageList] = useState([])
 const [imageType, setImageType] = useState(0)
 const [form] = Form.useForm()
 const [searchParams] = useSearchParams()
 const  articleId = searchParams.get('id')

 
   const onFinish = (values) => {
    
    if (imageType !== imageList.length) return message.warning('图片类型和数量不一致')
      // 调用接口
      const { title, channel_id, content } = values
      const params = {
        title,
        channel_id,
        content:content.html,
        cover:{
          type:imageType,
          images:imageList.map(item=>{
             if(item.response){
              return item.response.data.url
             }else{
               return item.url
             }
          })
      }
    }
     
    createOrUpdateAPI(params)
    }
    const createOrUpdateAPI =async(params)=>{
           if(articleId){
              //调用编辑接口
            await updateArticle({...params,id:articleId})
            message.success('更新成功')
            navigate('/aticle')
          }else{
            //调用新增接口
            creatArticleAPI(params).then(res => {
              message.success('新增成功')
              navigate('/aticle')
            })
          }
    }
    const checkPrice = (_, value) => {
      if (value.html !=='<p><br></p>') {
        return Promise.resolve();
      }
      return Promise.reject(new Error('内容不能为空!'));
    };
    const onUploadChange = (info) => {
      setImageList(info.fileList)
   }
   const onTypeChange = (e)=>{
          setImageType(e.target.value)
   }
  
   //回填数据
   useEffect(() => {
       function getArticle(){
        getArticleById(articleId).then((res)=>{
          //数据回填 setFieldsValue
          form.setFieldsValue({
            ...res.data,
            content:{html:res.data.content},
            type:res.data.cover.type,            
          })
          setImageType(res.data.cover.type)
          setImageList(res.data.cover.images.map(url=> { return {url}}))
        })
       }
       articleId&&getArticle()
    },[articleId,form]) 
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: articleId?'编辑文章':'发布文章' },
          ]}
          />
        }
      >
        <Form 
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0}}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title" 
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelList.map(item => {
                  return <Option value={item.id} key={item.id}>{item.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="封面">
          <Form.Item name="type">
            <Radio.Group onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {
            imageType>0&&<Upload
            name="image"
           listType="picture-card"
           showUploadList
           fileList={imageList}
           maxCount={3}
           action={'http://geek.itheima.net/v1_0/upload'}
           onChange={onUploadChange}
         >
           <div style={{ marginTop: 8 }}>
             <PlusOutlined />
           </div>
         </Upload>
          }
        </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            required
            rules={[{validator: checkPrice }] }
            validateTrigger="onSubmit"
          >
            {/* 富文本 */ }
            <Editor/> 
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>  
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish